// API工具类
const BASE_URL = 'http://localhost:8080/api';

interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  message?: string;
  [key: string]: any;
}

class ApiClient {
  private token: string = '';

  setToken(token: string) {
    this.token = token;
    wx.setStorageSync('token', token);
  }

  getToken(): string {
    if (!this.token) {
      this.token = wx.getStorageSync('token') || '';
    }
    return this.token;
  }

  clearToken() {
    this.token = '';
    wx.removeStorageSync('token');
  }

  private request<T>(options: {
    url: string;
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    data?: any;
    header?: any;
  }): Promise<ApiResponse<T>> {
    return new Promise((resolve, reject) => {
      const token = this.getToken();
      const header: any = {
        'Content-Type': 'application/json',
        ...options.header,
      };
      
      if (token) {
        header['Authorization'] = `Bearer ${token}`;
      }

      wx.request({
        url: BASE_URL + options.url,
        method: options.method || 'GET',
        data: options.data,
        header,
        success: (res: any) => {
          if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(res.data);
          } else {
            reject(new Error(res.data?.message || '请求失败'));
          }
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  }

  // 认证相关
  async login(username: string, password: string) {
    const res = await this.request<{ token: string; user: any }>({
      url: '/auth/login',
      method: 'POST',
      data: { username, password },
    });
    if (res.success && res.token) {
      this.setToken(res.token);
    }
    return res;
  }

  async register(username: string, password: string, nickname?: string) {
    const res = await this.request<{ token: string; user: any }>({
      url: '/auth/register',
      method: 'POST',
      data: { username, password, nickname },
    });
    if (res.success && res.token) {
      this.setToken(res.token);
    }
    return res;
  }

  async getCurrentUser() {
    return this.request({
      url: '/auth/me',
    });
  }

  async updateCurrentUser(data: { nickname?: string; avatar?: string }) {
    return this.request({
      url: '/auth/me',
      method: 'PUT',
      data,
    });
  }

  // 消息相关
  async sendMessage(message: any) {
    return this.request({
      url: '/messages/send',
      method: 'POST',
      data: message,
    });
  }

  async getConversation(otherUserId: number) {
    return this.request({
      url: `/messages/conversation/${otherUserId}`,
    });
  }

  async getRecentChats() {
    return this.request({
      url: '/messages/recent',
    });
  }

  async getUnreadMessages() {
    return this.request({
      url: '/messages/unread',
    });
  }

  async deleteMessage(messageId: number) {
    return this.request({
      url: `/messages/${messageId}`,
      method: 'DELETE',
    });
  }

  async markAsRead(messageId: number) {
    return this.request({
      url: `/messages/${messageId}/read`,
      method: 'PUT',
    });
  }

  async markConversationAsRead(otherUserId: number) {
    return this.request({
      url: `/messages/conversation/${otherUserId}/read`,
      method: 'PUT',
    });
  }

  // 联系人相关
  async getContacts() {
    return this.request({
      url: '/contacts/list',
    });
  }

  async addContact(qrCode: string) {
    return this.request({
      url: '/contacts/add',
      method: 'POST',
      data: { qrCode },
    });
  }

  async acceptContactRequest(requestId: number) {
    return this.request({
      url: `/contacts/${requestId}/accept`,
      method: 'PUT',
    });
  }

  async deleteContact(contactId: number) {
    return this.request({
      url: `/contacts/${contactId}`,
      method: 'DELETE',
    });
  }

  async getPendingRequests() {
    return this.request({
      url: '/contacts/pending',
    });
  }

  // 文件上传
  async uploadFile(filePath: string, fileType: 'VOICE' | 'IMAGE') {
    return new Promise((resolve, reject) => {
      const token = this.getToken();
      wx.uploadFile({
        url: BASE_URL + '/files/upload',
        filePath,
        name: 'file',
        formData: {
          fileType,
        },
        header: {
          Authorization: `Bearer ${token}`,
        },
        success: (res: any) => {
          try {
            const data = JSON.parse(res.data);
            resolve(data);
          } catch (e) {
            reject(e);
          }
        },
        fail: reject,
      });
    });
  }
}

export const api = new ApiClient();

